package cn.gzjp.modules.wx.service;

import java.io.File;
import java.io.StringReader;
import java.util.AbstractMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxMenu;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonHelper;
import me.chanjar.weixin.cp.api.WxCpConfigStorage;
import me.chanjar.weixin.cp.api.WxCpInMemoryConfigStorage;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import me.chanjar.weixin.cp.bean.WxCpUser;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonReader;

import cn.gzjp.modules.wx.entity.WxCorp;
import cn.gzjp.modules.wx.entity.WxCorpAgent;


/*

 * 本地与微信交互事务集合
 */
@Service
public class QyWxService {

	// Key 为corpid
	private AbstractMap<String, WxCpService> wxCpServices;

	private AbstractMap<String, WxCpConfigStorage> wxCpConfigStorages;
	
	@Autowired
	private WxCorpService wxCorpService;
	@Autowired
	private WxCorpAgentService wxCorpAgentService;

	public QyWxService() {
		this.wxCpServices = new ConcurrentHashMap<String, WxCpService>();
		this.wxCpConfigStorages = new ConcurrentHashMap<String, WxCpConfigStorage>();
	}

	/**
	 * 根据公众号，获取wxCpservice
	 * 
	 * @param corpid
	 * @return
	 */
	public WxCpService getWxCpService(String corpId, String agentId) {
		WxCpService wxCpService = this.wxCpServices.get(corpId + "_" + agentId);
		if (wxCpService == null) {
			this.updateCpConfig(corpId, agentId);
			wxCpService = this.wxCpServices.get(corpId + "_" + agentId);
		}
		return wxCpService;
	}

	/**
	 * 更新公众号信息到wxCpConfigStorages本地配置库
	 * 
	 * @param corpId
	 * @return
	 */
	public WxCpConfigStorage updateCpConfig(String corpId, String agentId) {
		/*
		 * CorpInfo c = new CorpInfo(); c.setCorpId("wx3a0b5ce9478e1365");
		 * c.setToken("tpfcWGrox4zlt9yY1DI2b1UUIgDd");
		 * c.setAesKey("R5HkHStyGVVjQNsKAUEcNR33ha5uxhR1wMQpSr481pb");
		 * c.setCorpSecret
		 * ("IY3JL3-fLv6BAhyFMozVlKhBADDm6FEVPzjJ05XG6v_wLQHoHXy5bQD3EVvIjZSA");
		 */

		WxCorpAgent agent = this.wxCorpAgentService.get(agentId);
		if (agent != null) {
			// 从agent应用中获取以下参数：corpId/corpSecret(主动请求微信时使用)/token/aeskey

			WxCpConfigStorage config = new WxCpInMemoryConfigStorage();
			BeanUtils.copyProperties(agent, config);
			
			//WxCorp corp=this.wxCorpService.get(agent.getCorpId());
			
			//BeanUtils.copyProperties(corp, config);
			this.wxCpConfigStorages.put(corpId + "_" + agentId, config);

			WxCpServiceImpl wxCpService = new WxCpServiceImpl();
			wxCpService.setWxCpConfigStorage(config);
			this.wxCpServices.put(corpId + "_" + agentId, wxCpService);

			return config;
		} else {
			return null;
		}
	}

	/**
	 * 从本地公众号配置库wxCpConfigStorages获取公众号信息
	 * 
	 * @param corpid
	 * @return
	 */
	public WxCpConfigStorage getWxCpConfigStorage(String corpId, String agentId) {
		WxCpConfigStorage wxCpConfigStorage = this.wxCpConfigStorages
				.get(corpId + "_" + agentId);
		if (wxCpConfigStorage == null) {
			wxCpConfigStorage = this.updateCpConfig(corpId, agentId);
		}
		return wxCpConfigStorage;
	}

	public void menuCreate(String corpId, String agentId, WxMenu menu)
			throws WxErrorException {
		WxCpService wxCpService = this.getWxCpService(corpId, agentId);
		wxCpService.menuCreate(agentId, menu);

	}

	public WxMenu menuGet(String corpId, String agentId)
			throws WxErrorException {
		WxCpService wxCpService = this.getWxCpService(corpId, agentId);
		return wxCpService.menuGet(agentId);
	}
	

	/**
	 * 获取部门列表
	 * @param corpId
	 * @return
	 * @throws WxErrorException
	 */
	public List<WxCpDepart> departGet(String corpId) throws WxErrorException {
		WxCpService wxCpService = this.wxCpServices.get(corpId);
		return wxCpService.departGet();
	}
	
	
	/**
	 * <pre>
	 * 根据useridl转换成openid
	 * https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid
	 * @param userid
	 * @param agentid 可选需要发送红包的应用ID，若只是使用微信支付和企业转账，则无需该参数
	 * @return
	 * @throws WxErrorException
	 * </pre>
	 */
//	public String convertUserIdToOpenid(String corpId,String agentid,String userid) throws WxErrorException {
//		WxCpService wxCpService = this.wxCpServices.get(corpId);
//		if(StringUtils.isNotBlank(agentid)){
//			wxCpService = this.getWxCpService(corpId,agentid);
//		}
//		return wxCpService.convertUserIdToOpenid(userid, agentid);
//	}

	/**
	 * <pre>
	 * 通过openid获取userid
	 * https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid
	 * @param openid 在使用微信支付、微信红包和企业转账之后，返回结果的openid
	 * @return
	 * @throws WxErrorException
	 * </pre>
	 */
//	public String convertOpenidTooUserid(String corpId,String agentid,String openid) throws WxErrorException {
//		WxCpService wxCpService = this.wxCpServices.get(corpId);
//		if(StringUtils.isNotBlank(agentid)){
//			wxCpService = this.getWxCpService(corpId,agentid);
//		}
//		return wxCpService.convertOpenidTooUserid(openid);
//	}
	
	  /**
	   * <pre>
	   * 用oauth2获取用户信息
	   * http://qydev.weixin.qq.com/wiki/index.php?title=根据code获取成员信息
	   * 因为企业号oauth2.0必须在应用设置里设置通过ICP备案的可信域名，所以无法测试，因此这个方法很可能是坏的。
	   *
	   * 注意: 这个方法使用WxCpConfigStorage里的agentId
	   * </pre>
	   * @see #oauth2getUserInfo(String, String)
	   *
	   * @param code
	   * @return [userid, deviceid]
	   */
	 public String[] oauth2getUserInfo(String corpId,String agentId,String code) throws WxErrorException{
		 WxCpService wxCpService = this.getWxCpService(corpId, agentId);
		    String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?"
		        + "code=" + code
		        + "&agendid=" + agentId;
		    String responseText = wxCpService.get(url, null);
		    JsonElement je = Streams.parse(new JsonReader(new StringReader(responseText)));
		    JsonObject jo = je.getAsJsonObject();
		    return new String[] {GsonHelper.getString(jo, "UserId"), GsonHelper.getString(jo, "DeviceId")};
	  }
	
	 
	  /**
	   * <pre>
	   * 发送消息
	   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=发送消息
	   * </pre>
	   *
	   * @param message
	   * @throws WxErrorException
	   */
	 public void messageSend(String corpId, String agentId,WxCpMessage message) throws WxErrorException{
		 WxCpService wxCpService = this.getWxCpService(corpId, agentId);
		 wxCpService.messageSend(message);
	 }
	 
	  /**
	   * 获取用户
	   *
	   * @param userid
	   * @return
	   * @throws WxErrorException
	   */
	 public WxCpUser userGet(String corpId,String userId) throws WxErrorException{
		 WxCpService wxCpService = this.wxCpServices.get(corpId);
		 return wxCpService.userGet(userId);
	  }
	 
	 public File mediaDownload(String corpId,String media_id) throws WxErrorException{
		 WxCpService wxCpService = this.wxCpServices.get(corpId);
		 return wxCpService.mediaDownload(media_id);
	 }
	 
	 public WxJsapiSignature getJsapiSignature(String corpId,String url)throws WxErrorException{
		 WxCpService wxCpService = this.wxCpServices.get(corpId);
		 return wxCpService.createJsapiSignature(url);
	 }
	 

}
